﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Flipmind.Xero;
using System.Net;
using System.IO;

namespace XeroInvoiceLoaderApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }



        /// <summary>
        /// Loads the chart of accounts and tracking categories
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnConnect_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            // Load the chart of accounts
            Account[] accounts = api.GetAccounts();
            lvAccounts.Items.Clear();
            foreach (Account account in accounts)
            {
                ListViewItem lvItem = new ListViewItem();
                lvItem.Text = account.Code;
                lvItem.SubItems.Add(account.Name);
                lvItem.SubItems.Add(account.Description);
                lvItem.SubItems.Add(account.TaxType.ToString());
                lvItem.SubItems.Add(account.Type.ToString());
                lvAccounts.Items.Add(lvItem);
            }
            // Load the tracking categories
            TrackingCategory[] tracking = api.GetTracking();
            lvTracking.Items.Clear();
            foreach (TrackingCategory t in tracking)
            {
                ListViewItem lvTrackingItem = new ListViewItem();
                lvTrackingItem.Text = t.Name;
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < t.Options.Count; i++ )
                {
                    TrackingCategoryOption opt = t.Options[i];
                    sb.Append(opt.Name);
                    if (i < t.Options.Count - 1)
                    {
                        sb.Append(", ");
                    }
                }
                lvTracking.Items.Add(lvTrackingItem);
            }
        }

        /// <summary>
        /// Loads all invoices and adds them to the grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInvoices_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            Invoice[] invoices = api.GetInvoices();
            lvInvoices.Items.Clear();
            foreach (Invoice invoice in invoices)
            {
                AddInvoiceToGrid(invoice);
            }
        }  

        private void AddInvoiceToGrid(Invoice invoice) {
            ListViewItem lvItem = lvInvoices.Items.Add(invoice.InvoiceNumber);
            lvItem.Tag = invoice.InvoiceID;
            lvItem.Text = invoice.InvoiceNumber;
            lvItem.SubItems.Add(invoice.Reference);
            lvItem.SubItems.Add(invoice.InvoiceType.ToString());
            lvItem.SubItems.Add(invoice.Contact.Name);
            lvItem.SubItems.Add(invoice.Total.ToString());
            
        }

        private void btnGetInvoiceById_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            Invoice invoice = api.GetInvoiceById(txtInvoiceID.Text);
            lvInvoices.Items.Clear();
            AddInvoiceToGrid(invoice);
        }

        private void btnGetContacts_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            Contact[] contacts = api.GetContactByType("customers");
            lvContacts.Items.Clear();
            foreach (Contact contact in contacts)
            {
                AddContactToGrid(contact);
            }
        }

        private void AddContactToGrid(Contact contact)
        {
            ListViewItem lvItem = new ListViewItem();
            lvItem.Tag = contact.ContactID;
            lvItem.Text = contact.Name;
            lvContacts.Items.Add(lvItem);
        }


        private void btnGetContact_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            Contact contact = api.GetContactById(txtContactID.Text);
            lvContacts.Items.Clear();
            AddContactToGrid(contact);
        }

        private void lvInvoices_DoubleClick(object sender, EventArgs e)
        {
            if (lvInvoices.SelectedItems.Count > 0)
            {
                XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
                string invoiceID = (string)lvInvoices.SelectedItems[0].Tag;
                EditInvoiceForm frm = new EditInvoiceForm();
                frm.ShowForm(api, invoiceID);
            }
        }

        private void btnCreateInvoice_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            EditInvoiceForm frm = new EditInvoiceForm();
            DialogResult result = frm.ShowForm(api);
            
        }

        private void lvContacts_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void lvContacts_DoubleClick(object sender, EventArgs e)
        {
            if (lvContacts.SelectedItems.Count > 0)
            {
                EditContactForm frm = new EditContactForm();
                XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
                Contact contact = api.GetContactById( (string) lvContacts.SelectedItems[0].Tag);
                frm.ShowForm(contact);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(textBox1.Text);
                string url = txtURL.Text;
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.UserAgent = "Xero API Client";
                request.KeepAlive = false;
                request.Method = "PUT";
                request.ContentType = "application/x-www-form-urlencoded";
                // set the timeout to 120 seconds
                request.Timeout = 120 * 1000;
                // set the content length in the request headers
                request.ContentLength = data.Length;
                // write the data to the imported into the request stream
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                }
                // get the response
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    if (request.HaveResponse == true && response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw new Exception("401, API Key is wrong");
                        }
                        // get the response stream and read it
                        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                        {
                            string output = reader.ReadToEnd();
                            txtResponse.Text = output;
                        }
                    }
                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show("Problem calling API: " + ex);
            }
            finally
            {

            }
        }

        private void btnCreateContact_Click(object sender, EventArgs e)
        {
            XeroAPI api = new XeroAPI(txtApiUrl.Text, txtAPIKey.Text, txtCustomerKey.Text);
            EditContactForm frm = new EditContactForm();
            frm.ShowForm(api);
        }

    }
}
